<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { updatePassword } from '/api/provide';
import { aesEncrypt } from '/utils/tools'
import { logout } from "/stores/user";

const formData = reactive({
	oldPassword: '',
	newPassword: '',
	confirmPassword: ''
})
const rules = {
	oldPassword: {
		rules: [
			{ required: true, errorMessage: '请填写原密码' }
		]
	},
	newPassword: {
		rules: [
			{ required: true, errorMessage: '请填写新密码' },
			{
				validateFunction: (rule, value, data, callback) => {
					if (value === data.oldPassword) {
						return '新密码不能和原密码相同'
					}
					if (value.length < 8 || value.length > 20) {
						return '新密码长度必须在 8-20 位之间'
					}
					return true
				}
			}
		]
	},
	confirmPassword: {
		rules: [
			{ required: true, errorMessage: '请确认新密码' },
			{
				validateFunction: (rule, value, data, callback) => {
					if (value !== data.newPassword) {
						return '两次输入的新密码不一致'
					}
					return true
				}
			}
		]
	}
}

const form = ref()
async function submit() {
	await form.value.validate()
	uni.showLoading()
	await updatePassword({
		oldPassword: aesEncrypt(formData.oldPassword),
		newPassword: aesEncrypt(formData.newPassword),
	})
	uni.hideLoading()
	await logout()
	uni.showToast({
		title: '密码修改成功',
		icon: 'none',
	})
}
</script>

<template>
	<view class="T_page T_form">
		<uni-forms ref="form" :modelValue="formData" :rules="rules" :label-width="100">
			<uni-forms-item name="oldPassword" label="原密码：">
				<uni-easyinput v-model="formData.oldPassword" type="password" placeholder="请输入原密码"
					v-bind="uni.$easyinput_attrs" />
			</uni-forms-item>
			<uni-forms-item name="newPassword" label="新密码：">
				<uni-easyinput v-model="formData.newPassword" type="password" placeholder="请输入新密码"
					v-bind="uni.$easyinput_attrs" />
			</uni-forms-item>
			<uni-forms-item name="confirmPassword" label="确认新密码：">
				<uni-easyinput v-model="formData.confirmPassword" type="password" placeholder="请再次输入新密码"
					v-bind="uni.$easyinput_attrs" />
			</uni-forms-item>
			<view class="tips">
				<view>密码要求：</view>
				<text>长度为 8-20 位字符</text>
			</view>
		</uni-forms>
		<button class="submit" type="primary" @click="submit">确认修改</button>
	</view>
</template>

<style lang="scss" scoped>
.tips {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
	color: #6B7280;
	font-size: 22rpx;
	margin-bottom: 20rpx;

	>text {
		&::before {
			content: '';
			width: 12rpx;
			height: 12rpx;
			background-color: currentColor;
			border-radius: 50%;
			display: inline-block;
			margin-right: 10rpx;
			vertical-align: middle;
		}
	}
}
</style>
